// #ifdef MP-ALIPAY
import config from '../../config.js';
import request from '../request.js'
import common from '../common.js'

let mpAlipay = {}

/*
 * 支付宝小程序获取OPENID
 * 2023-02-08
 */
mpAlipay.getOpenid = function() {
	let openid = uni.getStorageSync('openid')
	let user_id = uni.getStorageSync('user_id')

	return new Promise((resolve, reject) => {
		if (!openid) {
			mpAlipay.login().then(res => {
				resolve(res)
			}).catch(res => {
				reject()
			})
		} else {
			resolve({
				openid: uni.getStorageSync('openid'),
				user_id: uni.getStorageSync('user_id'),
			})
			console.log('生产环境 缓存:openid = ' + uni.getStorageSync('openid') + ' user_id = ' + uni
				.getStorageSync('user_id'))
		}

	})
}

mpAlipay.login = function() {
	return new Promise((resolve, reject) => {
		uni.getProvider({
			service: 'oauth',
			success: function(res) {
				if (~res.provider.indexOf('alipay')) {
					uni.login({
						provider: 'alipay',
						scopes: ['auth_base'],
						success: function(loginRes) {
							request.getData(
								'base/mpalipay/api/Auth/getOpenid', {
									code: loginRes.code
								}, {
									loading: true
								}).then(res => {
								uni.setStorageSync('openid', res.data
									.openid)
								uni.setStorageSync('user_id', res
									.data.user_id)
								uni.setStorageSync('access_token',
									res.data.access_token)
								uni.setStorageSync(
									'access_token_expire_time',
									res.data
									.access_token_expire_time)

								resolve({
									openid: uni
										.getStorageSync(
											'openid'),
									user_id: uni
										.getStorageSync(
											'user_id'),
								})

								console.log('生产环境刚获得 缓存:openid = ' +
									uni.getStorageSync(
										'openid') +
									' user_id = ' +
									uni.getStorageSync(
										'user_id'))
							}, err => {
								console.log(err)
								reject()
							})
						}
					})
				}
			}
		})
	})
}

export default mpAlipay
// #endif
